// const app = require('express')()


//导入数据库操作模块
const db = require("../../db/index.js")

// 格式化时间
var moment = require('moment')

/**
 * 获取申请列表
 * @param {*} req 
 * @param {*} res 
 */
exports.getApplicationList = async (req, res) => {
    console.log(req.query)
    let sql = ''
    let status = req.query.status
    let name = req.query.name
    let title = req.query.title
    let size = parseInt(req.query.limit)
    let start = (parseInt(req.query.page) - 1) * size
    let sqlArr = []
    if (!name || name == "") {
        if (!status || status == "" || status == 4 || status + "" == "全部") {
            sql = `SELECT COUNT(*) FROM xks_application AS application WHERE status != 0 AND application.title  = ?;
            SELECT * FROM xks_application AS application  WHERE status != 0 AND application.title  = ? limit ?,?`;
            sqlArr = [title, title, start, size]
        }
        else {
            console.log('status,' + status)
            sql = `SELECT COUNT(*) FROM xks_application AS application  WHERE status != 0 AND application.title  = ? AND application.status = ?;
            SELECT * FROM xks_application AS application  WHERE status != 0 AND application.title = ? AND application.status = ? limit ?,?`;
            sqlArr = [title, status, title, status, start, size]
        }

        db.query(sql, sqlArr, (err, results) => {
            if (err) {
                return res.send({
                    code: 505,
                    msg: '错误',
                    data: {}
                })
            }
            // 计算总页数
            var allCount = results[0][0]['COUNT(*)'];
            // console.log('results[0],', results[0])
            var allPage = parseInt(allCount) / size;
            var pageStr = allPage.toString();
            // 不能被整除
            if (pageStr.indexOf('.') > 0) {
                allPage = parseInt(pageStr.split('.')[0]) + 1;
            }
            var list = results[1];
            return res.send({
                code: 200,
                msg: '成功',
                totalPages: allPage,
                total: allCount,
                currentPage: start + 1,
                data: list
            })
        })
    } else {
        if (!status || status == "" || status == 3 || status == "全部") {
            // console.log('根据标题查,title=>', name, ',,,tag=>', tag)
            sql = `SELECT COUNT(*) FROM xks_application AS application  WHERE status != 0 AND application.title = ? AND application.name LIKE concat('%',?, '%');
            SELECT * FROM xks_application AS application  WHERE status != 0 AND application.title = ? AND application.name LIKE concat('%',?, '%')  limit ?,?`;
            sqlArr = [title, name, title, name, start, size]
        } else {
            sql = `SELECT COUNT(*) FROM xks_application AS application  WHERE status != 0 AND application.title = ? AND application.name LIKE concat('%',?, '%') AND  application.status =?;
            SELECT * FROM xks_application AS application  WHERE status != 0 AND application.title = ? AND application.name LIKE concat('%',?, '%')  AND application.status = ? limit ?,?`;
            sqlArr = [title, name, status, title, name, status, start, size]
        }
        db.query(sql, sqlArr, (err, results) => {
            if (err) {
                return res.send({
                    code: 505,
                    msg: '错误',
                    data: {}
                })
            }
            // 计算总页数
            var allCount = results[0][0]['COUNT(*)'];
            // console.log('results[0],', results[0])
            var allPage = parseInt(allCount) / size;
            var pageStr = allPage.toString();
            // 不能被整除
            if (pageStr.indexOf('.') > 0) {
                allPage = parseInt(pageStr.split('.')[0]) + 1;
            }
            var list = results[1];
            return res.send({
                code: 200,
                msg: '成功',
                totalPages: allPage,
                total: allCount,
                currentPage: start + 1,
                data: list
            })
        })
    }
}


/**
 * 增加申请
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.addApplication = (req, res) => {
    const Application = req.body;
    if (JSON.stringify(Application) == "{}") {
        console.log('【增加申请发送错误】' + 'req.body ===> ', req.body)
        return res.send({
            code: 400,
            msg: '因发送的请求语法错误,服务器无法正常读取。',
            data: {}
        })
    }
    else {
        if (!Application.title || !Application.name || !Application.major || !Application.contact) {
            return res.send({
                code: 400,
                msg: '有必填字段未填，请重新操作。',
                data: {}
            })
        }
    }

    //生成uuid
    let uuid1 = uuid.v1();
    // 去除横线-
    uuid1 = uuid1.replace(/-/g, '');
    // 添加id
    Application['id'] = uuid1;

    //发布时间
    let nowTime = new Date()
    var formatTime = moment(nowTime).format('YYYY-MM-DD HH:mm')
    console.log('申请时间', formatTime)
    Application['apply_time'] = formatTime;

    const addSql = `INSERT INTO xks_application SET ? `
    db.query(addSql, Application, (err, result) => {
        if (err) {
            console.log(err.message)
            return res.send({
                code: 505,
                msg: err.message,
                data: {}
            })
        }
        if (result.affectedRows !== 1) {
            return res.send({
                code: 500,
                msg: '增加失败，请稍后再试！',
                data: {}
            })
        }
        res.send({
            code: 200,
            msg: '增加成功',
            data: {}
        })
    })
}


/**
 * 删除申请
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.delApplication = (req, res) => {

    var Application = req.query;
    if (JSON.stringify(Application) == "{}") {
        console.log('【删除申请发送错误】' + 'req.body ===> ', req.body)
        return res.send({
            code: 400,
            msg: '因发送的请求语法错误,服务器无法正常读取。',
            data: {}
        })
    }
    else {
        if (!Application.id) {
            return res.send({
                code: 400,
                msg: '有必填字段未填，请重新操作。',
                data: {}
            })
        }
    }

    const findSql = `SELECT * FROM xks_application  WHERE status != 0 AND id = ?`;
    db.query(findSql, Application.id, (err, results) => {
        if (err) {
            return res.send({
                code: 505,
                msg: '发送了错误' + err.message,
                data: {}
            })
        }

        if (!results.length > 0) {
            return res.send({
                code: 400,
                msg: '没有找到该数据',
                data: {}
            })
        }

        Application = results[0]
        console.log('Application====>', Application)
        // 判断是否有操作的权限
        const admin = req.data
        if (!(Application.title + "").includes("极客")) {
            if (admin.level > '2') {
                console.log('没有权限，admin.level ===> ' + admin.level)
                return res.send({
                    code: 403,
                    msg: '对不起，没有权限删除该部门的内容！',
                    data: {}
                })
            }
        }

        const delSql = `UPDATE xks_application SET status = 0 WHERE id = ?`
        db.query(delSql, Application.id, (err, result) => {
            if (err) {
                console.log(err.message)
                return res.send({
                    code: 505,
                    msg: err.message,
                    data: {}
                })
            }
            if (result.affectedRows !== 1) {
                return res.send({
                    code: 500,
                    msg: '删除失败，请检查ID是否有误！',
                    data: {}
                })
            }
            res.send({
                code: 200,
                msg: '删除成功！',
                data: {}
            })
        })
    })
}


/**
 * 更新申请
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.updateApplication = (req, res) => {
    const Application = req.body;
    if (JSON.stringify(Application) == "{}") {
        console.log('【更新申请发送错误】' + 'req.body ===> ', req.body)
        return res.send({
            code: 400,
            msg: '因发送的请求语法错误,服务器无法正常读取。',
            data: {}
        })
    }
    else {
        if (!Application.title || !Application.name || !Application.contact || !Application.id) {
            return res.send({
                code: 400,
                msg: '有必填字段未填，请重新操作。',
                data: {}
            })
        }
    }

    // 判断是否有操作的权限
    const admin = req.data
    if (!(Application.title + "").includes("极客")) {
        if (admin.level > '2') {
            console.log('没有权限，admin.level ===> ' + admin.level)
            return res.send({
                code: 403,
                msg: '对不起，没有权限修改该部门的内容！',
                data: {}
            })
        }
    }

    //记录id的值
    const ApplicationId = Application.id
    delete Application.id

    const updateSql = `UPDATE xks_application SET ?  WHERE status != 0 AND id = ?`
    db.query(updateSql, [Application, ApplicationId], (err, result) => {
        if (err) {
            console.log(err.message)
            return res.send({
                code: 505,
                msg: err.message,
                data: {}
            })
        }
        if (result.affectedRows !== 1) {
            return res.send({
                code: 500,
                msg: '更新失败，请稍后再试！',
                data: {}
            })
        }
        res.send({
            code: 200,
            msg: '更新成功',
            data: {}
        })
    })
}